package com.vast.ui.component.socketinterface.server;


import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.vast.ui.component.socketinterface.request.RequestQueue;
import com.vast.ui.component.state.Sequence;
import com.vast.ui.component.util.ConsoleLoggerSingleton;
import com.vast.ui.component.util.Logger;
import com.vast.ui.panel.fullcolorled.Activator;

public class ReceiveService implements SocketService {
	 private final ExecutorService executorService = Executors.newSingleThreadExecutor();
	 private ServerSocket          serverRecvSocket = null;
	 private Socket                clientRecvSocket = null;
	 private DecodeRequester       decodeRequester;
	 private final Sequence        sequence;
	 private final RequestQueue    receivedQueue;
	 private final Logger          logger;
	 
	 public ReceiveService(Sequence sequence, RequestQueue  receivedQueue, DecodeRequester decodeRequester) {
		 this.sequence      = sequence;
	     this.receivedQueue = receivedQueue;
	     this.decodeRequester = decodeRequester;
	     this.logger        = ConsoleLoggerSingleton.getInstance();
	 }

     public void run() {
         if (!serverRecvSocket.isClosed()) {
             try {
            	 clientRecvSocket = serverRecvSocket.accept();
                 logger.writeEntry(Activator.PLUGIN_ID + ": Receive socket is accepted.");
                 executorService.execute(new ReceiveHandler(clientRecvSocket, sequence, receivedQueue, decodeRequester));
             } catch (Exception e) {
                 //e.printStackTrace();
             }
         }
     }
     
     public void startup(int port) {
    	 
         if (serverRecvSocket == null || serverRecvSocket.isClosed()) {
             try {
            	 serverRecvSocket = new ServerSocket(port);
                 new Thread(this).start();
                 logger.writeEntry(Activator.PLUGIN_ID + ": Start Receive Service. (port: " + port + ")");
             } catch (Exception e) {
                 try {
                	 serverRecvSocket.close();
                 } catch (Exception e2) {}
                 logger.writeEntry(Activator.PLUGIN_ID + ": Can not launch Receive Service.");
             }
         } else {
        	 logger.writeEntry(Activator.PLUGIN_ID + ": Receive Service is runnning.");
         }
     }
     
     public void shutdown() {
         if (serverRecvSocket != null && !serverRecvSocket.isClosed()) {
             try {
            	 serverRecvSocket.close();
                 logger.writeEntry(Activator.PLUGIN_ID + ": Receive service is stopped.");
             } catch (Exception e) {}
         } else {
        	 logger.writeEntry(Activator.PLUGIN_ID + ": Receive channel is not working.");
         }
     }	 
}
